package com.itee.core.serial;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author xin
 */
public class SerialHandler extends IoHandlerAdapter {

    public static final String NAME = "name";

    public static SerialHandler instance;

    public static SerialHandler getInstance() {
        if (instance == null) {
            instance = new SerialHandler();
        }
        return instance;
    }

    private final Map<Object, SerialSession> sessionMap = new HashMap<>();

    private SerialHandler() {}

    @Override
    public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
        cause.printStackTrace();
        session.close(true);
    }

    @Override
    public void sessionClosed(IoSession session) throws Exception {
        super.sessionClosed(session);
        synchronized (sessionMap) {
            sessionMap.remove(session.getAttribute(NAME));
        }
    }

    @Override
    public void messageReceived(IoSession session, Object message) throws Exception {
        SerialSession serialSession = sessionMap.get(session.getAttribute(NAME));
        serialSession.messageReceived(message);
    }

    public void addSession(SerialSession session) {
        sessionMap.put(session.getName(), session);
    }

    public SerialSession getSession(String name) {
        return sessionMap.get(name);
    }

    public boolean hasSession(String name) {
        return sessionMap.containsKey(name);
    }

    public void closeAllSessions() {
        List<SerialSession> dauSessions = new ArrayList<>();
        dauSessions.addAll(sessionMap.values());
        for (SerialSession dauSession : dauSessions) {
            dauSession.close();
        }
        dauSessions.clear();
    }
}
